package com.zmht.beike.web.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.zmht.beike.biz.TargetManageBiz;
import com.zmht.beike.biz.impl.TargetManageBizImpl;
import com.zmht.beike.core.BaseAction;
import com.zmht.beike.po.TCaiminfo;
import com.zmht.beike.po.TCaimtostudent;
import com.zmht.beike.po.TCareacontent;
import com.zmht.beike.util.AgeUtil;
import com.zmht.beike.web.form.CaiminfoForm;
import com.zmht.specedu.vo.Teacher;
//集体目标基本信息操作
public class CaiminfoAction extends BaseAction {

	/*
	 * 添加集体目标记录
	 * (non-Javadoc)
	 * @see org.apache.struts.actions.DispatchAction#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	public ActionForward addCaiminfo(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		//
		CaiminfoForm caiminfoForm = (CaiminfoForm)form;
		//HttpSession session = request.getSession();
	
		TCaiminfo info = new TCaiminfo();
		info.setParaType(caiminfoForm.getParaType());
		info.setParaValue(caiminfoForm.getParaValue());
		info.setTerm(caiminfoForm.getTerm());
		info.setEnactmenter(caiminfoForm.getEnactmenter());
		Teacher teacher = (Teacher)request.getSession().getAttribute("current_user_session_key");
		info.setTeacherId(teacher.getTeacherId());
		info.setEnactmentDate(caiminfoForm.getEnactmentDate());
		
		//info.setAreaId(areaId)
		
		info.setType(1);//自定义目标 0 为系统目标
		info.setShare(1);//是否分享 默认为1
		info.setDisabled(1);//是否可用 默认1
		info.setConcount(0); //默认收藏为0
		info.setTeacherId(teacher.getTeacherId());
		if(caiminfoForm.getParaType().equals(2)){
			info.setParaValue(caiminfoForm.getAge());
		}
		//设置目标名称
		info.setCaiminfoName(AgeUtil.getClassName(info.getParaValue())+"（"+AgeUtil.getAge(info.getParaValue())+"）"+teacher.getTname()+" 的教学目标");
		
		
		
		//同时更新领域目标内容
		List<TCareacontent> list = new ArrayList();
		
	
		list.addAll(this.getCareaContentBiz().findAreaContent(request.getSession().getId(), 1, 0, 100));
		list.addAll(this.getCareaContentBiz().findAreaContent(request.getSession().getId(), 2, 0, 100));
		list.addAll(this.getCareaContentBiz().findAreaContent(request.getSession().getId(), 3, 0, 100));
		list.addAll(this.getCareaContentBiz().findAreaContent(request.getSession().getId(), 4, 0, 100));
		list.addAll(this.getCareaContentBiz().findAreaContent(request.getSession().getId(), 5, 0, 100));
		
		//根据班级 学期 教师ID 活动目标ID（如果存在目标 则更新即可）
		List<TCaiminfo> infos = this.getCareaContentBiz().findByHQL("from TCaiminfo t where t.paraValue='"+info.getParaValue()+"' and t.teacherId="+info.getTeacherId()+" and t.term="+info.getTerm());
		if(null!=infos&&infos.size()>0)
		{
			info = infos.get(0);
		}
		this.saveAreaInfo(list, info, request, teacher);
		/*this.saveAreaInfo(list2, info, request, teacher,2);
		this.saveAreaInfo(list3, info, request, teacher,3);
		this.saveAreaInfo(list4, info, request, teacher,4);
		this.saveAreaInfo(list5, info, request, teacher,5);
		*/
		
		
		//return mapping.findForward("addMubiao");
		return new ActionForward("/beike/caiminfo.do?method=getCaiminfo");
	}
	
	/**
	 * 保存领域信息，学生领域目标对照信息
	 * @param list
	 * @param info
	 * @param request
	 * @param teacher
	 */
	private void saveAreaInfo(List<TCareacontent> list,TCaiminfo info,HttpServletRequest request,Teacher teacher){
		if(list!=null&&list.size()>0){
			info.setAreaId(list.get(0).getAreaType());
			Integer id  = null;
			if(info.getId()==null){
				id = (Integer)this.getCaiminfoBiz().save(info);
			}else{
				id = info.getId();
			}
			for(TCareacontent carea:list){
				carea.setCaimId(id);
				this.getCareaContentBiz().upTCareacontent(carea);
			}
			//添加目标 和 学生记录信息
			String [] studentids = request.getParameterValues("student");
			if(studentids!=null&&studentids.length>0){
				for(String s:studentids){
					TCaimtostudent bean = new TCaimtostudent();
					bean.setCaimId(id);
					bean.setTeacherId(teacher.getTeacherId());
					bean.setStudentId(new Integer(s));
					
					this.getCaimtostudentBiz().saveTCaimtostudent(bean);
				}
			}
		}
		
	}
	/**
	 * 查询 集体目标信息
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward getCaiminfo(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		//获得当前登录老师
		Teacher teacher = (Teacher)request.getSession().getAttribute("current_user_session_key");
			
		Integer index = 1;
		Integer size = 5;
		if(null!=request.getParameter("currPage")){
			index = new Integer(request.getParameter("currPage"));
		}
		if(null!=request.getParameter("pageSize")){
			size = new Integer(request.getParameter("pageSize"));
		}
		//List list = this.getCaiminfoBiz().getCaiminfo((index-1)*size, size, teacher.getTeacherId()+"");
		
		//改为生sql查询添加有领域内容的目标记录 目标id，班级，年龄，学期，领域id，创建时间
		//select distinct c.id,c.caiminfoName,c.paraValue,c.paraValue,c.term,ct.AreaType,c.enactmentDate from t_caiminfo c,t_careacontent ct where c.id = ct.caimID and c.teacherID=3
		//int total = this.getCaiminfoBiz().getCaiminfoTotal((index-1)*size, size, teacher.getTeacherId()+"");
		
		String sql = "select distinct c.id,c.caiminfoName,c.paraValue,c.paraValue,c.term,ct.AreaType,c.enactmentDate,ct.AreaType from t_caiminfo c,t_careacontent ct where c.id = ct.caimID and c.teacherID="+teacher.getTeacherId()+" order by ct.id desc";
		List<Object[]> list = this.getCaiminfoBiz().findBySQL(sql,(index-1)*size,size);//.findBySQL(sql);
		if(null!=list&&list.size()>0){//将数字转换成文字
			for(Object[] obj:list){
				obj[3] = AgeUtil.getClassName(obj[3].toString());
				obj[2] = AgeUtil.getAge(obj[2].toString());
				obj[4] = AgeUtil.getTerm(obj[4].toString());
				obj[5] = AgeUtil.getAreaName(obj[5].toString());
			}
		}
		
		int total = this.getCaiminfoBiz().findBySQLTotal(sql);
		
		request.setAttribute("currPage", index); 
		request.setAttribute("pageAmount", (int)Math.ceil(total/new Double(size)));
		request.setAttribute("pageSize", size);
		
		request.setAttribute("tname", teacher.getTname());
		request.setAttribute("caiminfos", list);
		
		return mapping.findForward("target");
	}
	/**
	 * 共享目标 ajax调用
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward shareCaiminfo(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		String id = request.getParameter("cid");
		TCaiminfo caiminfo = this.getCaiminfoBiz().findById(new Integer(id));
		if(null!=caiminfo){
			caiminfo.setShare(1);
			this.getCaiminfoBiz().updateCaiminfo(caiminfo);
		}
		java.io.PrintWriter out = response.getWriter();
		
		out.print("test");
		out.close();
		return null;
	}
	/**
	 * 初始化集体目标编辑页面
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward initCaiminfoEdit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		String targetId = request.getParameter("targetId");
		Teacher teacher = (Teacher)request.getSession().getAttribute("current_user_session_key");
		List list = this.getCareaContentBiz().getCareaContentDAO().findBySql("select s.StudentId,s.SName,s.ClassID from classteacher ct,student s where s.ClassID=ct.ClassID and ct.TeacherID = "+teacher.getTeacherId());
		
		request.setAttribute("teacherName", teacher.getTname());
		request.setAttribute("students", list);
		TCaiminfo caiminfo = this.getCaiminfoBiz().findById(new Integer(targetId));
		request.setAttribute("caiminfo", caiminfo);
		return new ActionForward("/jsp/mubiaozhiding/editMubiao.jsp?targetId="+targetId);
	
	}
	/**
	 * 编辑页面点击保存时 更新内容
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward editCaiminfo(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		//编辑目标
		CaiminfoForm caiminfoForm = (CaiminfoForm)form;
		TCaiminfo info = this.getCaiminfoBiz().findById(new Integer(request.getParameter("targetId")));
		info.setParaType(caiminfoForm.getParaType());
		info.setParaValue(caiminfoForm.getParaValue());
		info.setTerm(caiminfoForm.getTerm());
		info.setEnactmenter(caiminfoForm.getEnactmenter());
		info.setEnactmentDate(caiminfoForm.getEnactmentDate());
			
		this.getCaiminfoBiz().updateCaiminfo(info);
		
		return new ActionForward("/beike/caiminfo.do?method=getCaiminfo");
	}
	public static void main(String [] args){
		ApplicationContext cxt;
		cxt = new ClassPathXmlApplicationContext(new String[]{"spring/spring.xml","spring/spring_dao.xml","spring/spring_beike.xml",});
		TargetManageBiz biz = (TargetManageBizImpl)cxt.getBean("targetManagerBizTag");
		System.out.println(biz.deleteByHQL("delete from TCaiminfo t where t.id=10"));
	}
}
